package eu.webhib.frmwrk.jsf.utils;

import javax.faces.application.*;
import javax.faces.context.FacesContext;
import java.text.MessageFormat;
import java.util.*;
import org.apache.log4j.Logger;

public class ResUtil {

   private static final Logger log = Logger.getLogger(ResUtil.class);
   private static final String appBundleName = "msg";

   private ResUtil() {
   }

   public static String getResourceText(FacesContext ctx, String bundleName, String key, Object... args) {
      Application app = ctx.getApplication();
      ResourceBundle bundle = app.getResourceBundle(ctx, bundleName);
      return getResourceText(bundle, key, args);
   }

   public static String getResourceText(ResourceBundle bundle, String key, Object... args) {
      String text;
      try {
         text = bundle.getString(key);
      } catch (Exception ex) {
         log.error("could not find text resource '" + key + "'");
         return "?" + key + "?";
      }
      if (args != null) {
         text = MessageFormat.format(text, args);
      }
      return text;
   }

   public static String getResourceText(String key, Object... args) {
      return getResourceText(FacesContext.getCurrentInstance(), appBundleName, key, args);
   }
}
